package saucaca.fragment;

import java.util.Calendar;

import org.json.JSONException;

import saucaca.CustomView.CircularImageView;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.AccountObject;
import saucaca.Object.HomeData;
import saucaca.Util.AppController;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RemoteControlClient;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.lemon.kenhnhacvn.BaseActivity;
import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;

public class AccountUpdateInfoFragment extends Fragment {
	String TAG = AccountRegisterFragment.class.getSimpleName();

	private static final int SELECT_PICTURE = 1;
	String imagePath = "";
	private MainActivity mActivity = null;
	Resources resources;
	TextView txtAvatarPath;
	EditText edtFullname, edtPhone, edtBirthday, edtPassOld, edtPassNew, edtPassNew2;
	CircularImageView account_avatar, account_avatarChoose;
	String day, month, year;
	RadioGroup radioGroup;
	String strAvatar,strAvatar_url, userName, fullName, birthday, phone, sex;
	Bitmap bitmap;
	ImageLoader imageLoader;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// getActivity().getActionBar().hide();
		resources = getResources();
		View view = inflater.inflate(R.layout.account_updateinfo, container, false);
		findViewById(view);
		try {
			imageLoader=((BaseActivity)mActivity).imageLoader;
		} catch (Exception ex) {
			imageLoader=AppController.getInstance().getImageLoader();
		}
		strAvatar = PreferenceUtils.getString(mActivity, TagName.KeyPreference_avatar);
		strAvatar_url = PreferenceUtils.getString(mActivity, TagName.KeyPreference_avatar_url);
		userName = PreferenceUtils.getString(mActivity, TagName.KeyPreference_user);
		fullName = PreferenceUtils.getString(mActivity, TagName.KeyPreference_fullname);
		birthday = PreferenceUtils.getString(mActivity, TagName.KeyPreference_birthday);
		phone = PreferenceUtils.getString(mActivity, TagName.KeyPreference_phone);
		sex = PreferenceUtils.getString(mActivity, TagName.KeyPreference_sex);
		if (strAvatar != null) {
			try {
				Bitmap bitmap = BaseEngine.BitmapFromBase64(strAvatar);
				account_avatar.setImageBitmap(bitmap);
			} catch (Exception e) {
				if (BaseEngine.isConnectionAvailable(mActivity) && strAvatar_url!=null) {
//					ImageLoader.getInstance().loadImage(strAvatar_url, new SimpleImageLoadingListener() {
//						@Override
//						public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//							super.onLoadingComplete(imageUri, view, loadedImage);
//							account_avatar.setImageBitmap(loadedImage);
//						}
//					});
					imageLoader.get(HomeData.homeAccount.getAVATAR(), new ImageLoader.ImageListener() {
				        @Override
				        public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
				        	account_avatar.setImageBitmap(response.getBitmap());
				        }

						@Override
						public void onErrorResponse(VolleyError arg0) {
						}
				    });
					
				}
			}
		}
		if (fullName != null) {
			edtFullname.setText(fullName);
		}
		if (birthday != null) {
			edtBirthday.setText(birthday);
		}
		if (phone != null) {
			edtPhone.setText(phone);
		}
		if (sex != null) {
			String _sex = BaseEngine.convertStringLongtoInteger(sex);
			if (_sex.equals("1")) {
				radioGroup.check(R.id.personalprofile_Nam);
			} else if (_sex.equals("2")) {
				radioGroup.check(R.id.personalprofile_Nu);
			} else if (_sex.equals("0")) {
				radioGroup.check(R.id.personalprofile_Other);
			}
		}
		 new getinfoAsyns().execute("");
			mActivity.myActionBar.setMenu(R.string.account_info, false, true);
			return view;
		}
		@Override
		public void onHiddenChanged(boolean hidden) {
			super.onHiddenChanged(hidden);
			mActivity.myActionBar.setMenu(R.string.account_info, false, true);
		}

	public void findViewById(View view) {
		radioGroup = (RadioGroup) view.findViewById(R.id.acount_update_radiogroup);
		txtAvatarPath = (TextView) view.findViewById(R.id.account_avatarchoose_Text);
		edtFullname = (EditText) view.findViewById(R.id.account_edt_fullname);
		edtBirthday = (EditText) view.findViewById(R.id.account_edt_birthday);
		edtPhone = (EditText) view.findViewById(R.id.account_edt_phonenumber);
		edtPassOld = (EditText) view.findViewById(R.id.account_edt_passold);
		edtPassNew = (EditText) view.findViewById(R.id.account_edt_passnew);
		edtPassNew2 = (EditText) view.findViewById(R.id.account_edt_passrenew);
		account_avatar = (CircularImageView) view.findViewById(R.id.account_avatar);
		account_avatarChoose = (CircularImageView) view.findViewById(R.id.account_avatarchoose);
		account_avatar.setOnClickListener(clickListener);
		edtBirthday.setOnClickListener(clickListener);
		((Button) view.findViewById(R.id.account_buttonChooseAvatar)).setOnClickListener(clickListener);
		((LinearLayout) view.findViewById(R.id.account_button_updateinfo)).setOnClickListener(clickListener);
		((LinearLayout) view.findViewById(R.id.account_button_changepass)).setOnClickListener(clickListener);
		edtBirthday.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					showDatedialog();
				}
			}
		});
	}

	View.OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.account_avatar:
				chooseImage();
				break;
			case R.id.account_buttonChooseAvatar:
				chooseImage();
				break;	
			case R.id.account_button_updateinfo:
				if (bitmap != null)
					new updateAvatar().execute("");
				new updateinfoAsyns().execute("");
				break;
			case R.id.account_button_changepass:
				if (!edtPassOld.getText().toString().equals("") && !edtPassNew.getText().toString().equals("") && !edtPassNew2.getText().toString().equals("")) {
					if (edtPassNew.getText().toString().equals(edtPassNew2.getText().toString())) {
						new changePassAsyns().execute("");
					} else
						TagName.showToastShort(mActivity, "Nhập lại mật khẩu không đúng!");
				} else
					TagName.showToastShort(mActivity, "Bạn phải nhập đủ thông tin!");
				break;
			case R.id.account_edt_birthday:
				showDatedialog();
				break;
			default:
				break;
			}
		}
	};

	public void chooseImage() {
//		Intent intent = new Intent();
//		intent.setType("image/*");
//		intent.setAction(Intent.ACTION_GET_CONTENT);
//		startActivityForResult(Intent.createChooser(intent, "Thay đổi avatar"), SELECT_PICTURE);
		Intent i = new Intent(
				Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(i, SELECT_PICTURE);
	}

	@SuppressWarnings("static-access")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
			switch (requestCode) {
			case SELECT_PICTURE:

				if (requestCode == SELECT_PICTURE && resultCode == mActivity.RESULT_OK && null != data) {
					Uri selectedImage = data.getData();
					String[] filePathColumn = { MediaStore.Images.Media.DATA };
					Cursor cursor = mActivity.getContentResolver().query(selectedImage,
							filePathColumn, null, null, null);
					cursor.moveToFirst();

					int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
					String picturePath = cursor.getString(columnIndex);
					cursor.close();
					bitmap = BitmapFactory.decodeFile(picturePath);
					if (bitmap != null) {
						txtAvatarPath.setText(imagePath);
						account_avatarChoose.setImageBitmap(bitmap);
					}
//					else{
//						String http="http";
//						String path=imagePath.substring(imagePath.lastIndexOf(http));
//						TagName.showLogError("Updateinfo","path:"+ path);
//						ImageLoader.getInstance().loadImage(path, new SimpleImageLoadingListener() {
//							@Override
//							public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//								super.onLoadingComplete(imageUri, view, loadedImage);
////								PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(mActivity, loadedImage));
//								txtAvatarPath.setText(imagePath);
//								bitmap = loadedImage;
//								account_avatarChoose.setImageBitmap(bitmap);
//							}
//						});
//					}
				}
				break;
			}
//			if (resultCode == mActivity.RESULT_OK) {
//			if (requestCode == SELECT_PICTURE) {
//				try {
//					Uri selectedImageUri = data.getData();
//					imagePath = selectedImageUri.getPath();
////					TagName.showLogError("Updateinfo", imagePath);
//					bitmap = BitmapFactory.decodeFile(imagePath);
//					if (bitmap != null) {
//						txtAvatarPath.setText(imagePath);
//						account_avatarChoose.setImageBitmap(bitmap);
//					}else{
//						String http="http";
//						String path=imagePath.substring(imagePath.lastIndexOf(http));
//						TagName.showLogError("Updateinfo","path:"+ path);
//						ImageLoader.getInstance().loadImage(path, new SimpleImageLoadingListener() {
//							@Override
//							public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//								super.onLoadingComplete(imageUri, view, loadedImage);
////								PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(mActivity, loadedImage));
//								txtAvatarPath.setText(imagePath);
//								bitmap = loadedImage;
//								account_avatarChoose.setImageBitmap(bitmap);
//							}
//						});
//					}
//				} catch (Exception e) {
//				}
//			}
//		}
	}

	public void showDatedialog() {
		final Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);

		DatePickerDialog dpd = new DatePickerDialog(mActivity, new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				edtBirthday.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
			}
		}, year, month, day);
		dpd.show();
	}

	String checkSexchecked() {
		int intcheck = radioGroup.indexOfChild(radioGroup.findViewById(radioGroup.getCheckedRadioButtonId()));
		switch (intcheck) {
		case 1:
			return "2";
		case 2:
			return "0";
		default:
			return "1";
		}
	}

	class updateinfoAsyns extends AsyncTask<String, String, String> {
		ProgressDialog dialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... params) {
			String fullName = edtFullname.getText().toString();
			String sex = checkSexchecked();
			String birthDay = BaseEngine.checkDate(edtBirthday.getText().toString());
			String phone = edtPhone.getText().toString();
			String str = WServiceLib.account_updateinfo(userName, fullName, sex, birthDay, phone);

			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!dialog.isShowing()) {
				dialog.show();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.hide();
			}
			if (result != null) {
//				 BaseEngine.showLogformLongString(result);
				try {
					JsonReader.readHeader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (HomeData.headerObject != null) {
				TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
			}
		}
	}

	class updateAvatar extends AsyncTask<String, String, String> {
		ProgressDialog dialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.account_uploadAvatar(BaseEngine.BitmapTobase64(bitmap), userName, "0");
//			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!dialog.isShowing()) {
				dialog.show();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			String avatar="";
			if (dialog.isShowing()) {
				dialog.hide();
			}
			if (result != null) {
				try {
					JsonReader.readHeader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (HomeData.headerObject != null&& HomeData.headerObject.getCODE().equals("0")) {
				try {
					avatar=JsonReader.UserUpdateAvatar(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
//				PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(bitmap));
				PreferenceUtils.remove(mActivity, TagName.KeyPreference_avatar);
				PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar_url, avatar);
//				ImageLoader.getInstance().displayImage(avatar, account_avatar);
				imageLoader.get(avatar, ImageLoader.getImageListener( account_avatar,
	         R.drawable.ic_default, R.drawable.ic_default));
				mActivity.menuFragment.changedLoginstatus(true);
			}
		}
	}

	class getinfoAsyns extends AsyncTask<String, String, String> {
		ProgressDialog dialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.account_info(userName);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!dialog.isShowing()) {
				dialog.show();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			
			if (dialog.isShowing()) {
				dialog.hide();
			}
			if(result!=null){
//				BaseEngine.showLogformLongString(result);
				try {
					JsonReader.readHeader(result);
					if(HomeData.headerObject != null&& HomeData.headerObject.getCODE().equals("0"))
						showInfoAccount(JsonReader.readUserInfo(result));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
	}

	void showInfoAccount(AccountObject accountObject){
		if(accountObject!=null){
//			BaseActivity.imageLoader.displayImage(accountObject.getAVATAR(), account_avatar, BaseActivity.options);
//			ImageLoader.getInstance().loadImage(accountObject.getAVATAR(), new SimpleImageLoadingListener() {
//				@Override
//				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//					super.onLoadingComplete(imageUri, view, loadedImage);
//					account_avatar.setImageBitmap(loadedImage);
//				}
//			});
			imageLoader.get(HomeData.homeAccount.getAVATAR(), new ImageLoader.ImageListener() {
		        @Override
		        public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
		        	account_avatar.setImageBitmap(response.getBitmap());
		        }

				@Override
				public void onErrorResponse(VolleyError arg0) {
				}
		    });
		edtFullname.setText(accountObject.getFULL_NAME());
		edtBirthday.setText(accountObject.getBIRTH_DAY());
		edtPhone.setText(accountObject.getMOBILE());
		if (accountObject.getSEX() != null) {
			String _sex = BaseEngine.convertStringLongtoInteger(accountObject.getSEX());
			if (_sex.equals("1")) {
				radioGroup.check(R.id.personalprofile_Nam);
			} else if (_sex.equals("2")) {
				radioGroup.check(R.id.personalprofile_Nu);
			} else if (_sex.equals("0")) {
				radioGroup.check(R.id.personalprofile_Other);
			}
		}
	}}
	

	class changePassAsyns extends AsyncTask<String, String, String> {
		ProgressDialog dialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... params) {
			String passOld = edtPassOld.getText().toString();
			String passNew = edtPassNew.getText().toString();
			String str = WServiceLib.account_changePass(userName, passOld, passNew);
//			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!dialog.isShowing()) {
				dialog.show();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.hide();
			}
			if (result != null) {
				// BaseEngine.showLogformLongString(result);
				try {
					JsonReader.readHeader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (HomeData.headerObject != null) {
				if (HomeData.headerObject.getCODE().equals("0")) {
					edtPassOld.setText("");
					edtPassNew.setText("");
					edtPassNew2.setText("");
				}
				TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
			}
		}

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof MainActivity) {
			mActivity = (MainActivity) activity;
		}
	}
}